import itchat
import requests
import json
import random
from itchat.content import *

SEND_CONTRACT = (
    '一只小明'
)

BOOT_URL = 'http://i.itpk.cn/api.php?question={}&api_key=4a0ba7844e977f70487504d95a8c3d42&api_secret=u9vfwzz4k54p'

def login_in():
    print('机器人已启动...')


def process_text(msg):
    if '笑话' in msg:
        text = requests.get(BOOT_URL.format('笑话')).text
        text = text.encode('ascii','ignore').decode(encoding='utf-8')
        data = json.loads(text)
        title = data['title']
        content = data['content']

        return title + '\n\n' + content
    elif '观音灵签' in msg:
        text = requests.get(BOOT_URL.format(msg)).text
        text = text.encode('ascii','ignore').decode(encoding='utf-8')
        data = json.loads(text)

        return '灵签类型：' + data['type'] + ' 签号：' + data['number'+str(random.randint(1,2))] + '\r\n\r\n' \
            + data['haohua'] + '\r\n\r\n' \
            + data['qianyu'] + '\r\n\r\n' \
            + data['shiyi'] + '\r\n\r\n' \
            + data['jieqian']

        
    elif '月老灵签' in msg:
        text = requests.get(BOOT_URL.format(msg)).text
        text = text.encode('ascii','ignore').decode(encoding='utf-8')
        data = json.loads(text)

        return '灵签类型：' + data['type'] + ' 签号：' + data['number'+str(random.randint(1,2))] + '\r\n\r\n' \
            + data['haohua'] + '\r\n\r\n' \
            + data['shiyi'] + '\r\n\r\n' \
            + data['jieqian'] + '\r\n\r\n' \
            + data['zhushi'] + '\r\n\r\n' \
            + data['baihua'] 

    elif '财神爷灵签' in msg:
        text = requests.get(BOOT_URL.format(msg)).text
        text = text.encode('ascii','ignore').decode(encoding='utf-8')
        data = json.loads(text)

        return '灵签类型：' + data['type'] + ' 签号：' + data['number'+str(random.randint(1,2))] + '\r\n\r\n' \
            + data['qianyu'] + '\r\n\r\n' \
            + data['zhushi'] + '\r\n\r\n' \
            + data['jieqian'] + '\r\n\r\n' \
            + data['jieshuo'] + '\r\n\r\n' \
            + data['jieguo'] + '\r\n\r\n' \
            + data['hunyin'] + '\r\n\r\n' \
            + data['jiaoyi']
    else:
        return requests.get(BOOT_URL.format(msg)).text

    

@itchat.msg_register(TEXT)
def _(msg):
    print(msg)
    return process_text(msg.text)


if __name__ == '__main__':
    itchat.auto_login(loginCallback=login_in,hotReload=True)
    itchat.run(True)
